package com.thingcom.chinamobile.factory;

import com.ctg.ag.sdk.biz.AepDeviceManagementClient;
import com.ctg.ag.sdk.core.BaseApiClient;
import com.ctg.ag.sdk.core.BaseApiClientBuilder;
import com.thingcom.chinamobile.util.ConfigAnalyze;
import com.thingcom.chinamobile.util.PropertyConfigAnalyze;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName ApiClientFactory
 * @Description API请求的工厂类
 * @Author zhou tao
 * @Date 2019/12/16 15:41
 * @Version 1.0
 **/
@Slf4j
public class ApiClientFactory {

	/**构造好的API请求对象集合*/
	private static Map<String, BaseApiClient> syncApiClientMap = new ConcurrentHashMap<>();
	private static Map<String, BaseApiClient> asyncApiClientMap = new ConcurrentHashMap<>();

	static {
		ConfigAnalyze analyze = new PropertyConfigAnalyze();
		Map<String, String> params = new HashMap<>();
		params = analyze.analyze("app.properties");

		String[] appKeys = params.get("app-key").split(",");
		String[] appSecrets= params.get("app-secret").split(",");
		String[] classNames = params.get("api-client-class").split(",");
		String packageName = params.get("api-client-package");
		// 循环遍历配置项，针对每个 appkey都初始化好配置的APIClinet对象
		for (int i = 0; i < appKeys.length; i++) {
			for (String className : classNames) {
				syncApiClientMap.put(appKeys[i] + className, newInstance(packageName + "." + className, appKeys[i], appSecrets[i]));
			}
		}
	}

	/**
	 * 根据类名创建API客户端请求对象
	 * @param className 完整的类名，包名 + 类名
	 * @return API请求对象
	 */
	private static BaseApiClient newInstance(String className, String appKey, String appSecret) {
		Method createMethed = null;
		try {
			createMethed = Class.forName(className).getMethod("newClient");
		} catch (NoSuchMethodException | ClassNotFoundException e) {
			log.error("方法加载出错, 原因: {}", e.getMessage());
		}

		Object result = null;
		try {
			result = createMethed.invoke(null);
		} catch (IllegalAccessException | InvocationTargetException e) {
			log.error("方法调用出错, 原因: {}", e.getMessage());
		}

		return ((BaseApiClientBuilder)result).appKey(appKey).appSecret(appSecret).build();
	}

	/**
	 * 获取API请求对象
	 * @param id appKey + 类名
	 * @param isAsync 是否异步调用
	 * @return 对应的请求对象
	 */
	public static BaseApiClient getInstance(String id, boolean isAsync) {
		return isAsync ? asyncApiClientMap.get(id) : syncApiClientMap.get(id);
	}

	/**
	 * 同步调用获取API请求对象
	 * @param id appKey + 类名
	 * @return API请求对象
	 */
	public static BaseApiClient getInstance(String id) {
		return getInstance(id, false);
	}
}
